import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    // 四数之和
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        int len = nums.length;
        if(len < 4) {
            return ret;
        }
        // 排序
        Arrays.sort(nums);
        int i = 0;
        while(i < len - 3) {
            int j = i + 1;
            while(j < len - 2) {
                int left = j + 1;
                int right = len - 1;
                long t = (long)target - nums[i] - nums[j];
                while(left < right) {
                    if(nums[left] + nums[right] < t) {
                        left++;
                    } else if(nums[left] + nums[right] > t){
                        right--;
                    } else {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        ret.add(list);
                        // 去除左边重复元素
                        left++;
                        while(left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        // 去除右边重复元素
                        right--;
                        while(left < right && nums[right] == nums[right+1]) {
                            right--;
                        }
                    }
                }
                j++;
                while(j < len - 2 && nums[j] == nums[j - 1]) {
                    j++;
                }
            }
            i++;
            while(i < len - 3 && nums[i] == nums[i - 1]) {
                i++;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {1,0,-1,0,-2,2};
        Solution solution = new Solution();
        solution.fourSum(nums, 0);
    }
}